package com.lngsyz.file.service.source1;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.lngsyz.file.entity.source1.SystemFileupload;
import com.lngsyz.file.exception.RequestSystemException;
import com.lngsyz.file.mapper.source1.SystemFileuploadMapper;
import com.lngsyz.file.util.CommonUtil;
import com.lngsyz.file.util.FileUtil;
import com.lngsyz.file.util.StringUtil;

@Service
public class SystemFileuploadService {
    
	@Autowired
	SystemFileuploadMapper systemFileuploadMapper;
	
	@Value("${key-properties.file-local-path}")
	private String fileLocalPath = "";
	@Value("${key-properties.file-local-folder}")
	private String fileLocalFolder = "";
	
	@Transactional(rollbackFor = Exception.class)
	public void insert(SystemFileupload systemFileupload) {
		if(systemFileupload != null) {
			systemFileuploadMapper.insert(systemFileupload);
		}
	}
	
	public SystemFileupload findById(String id){
		if(StringUtils.isNotBlank(id)) {
			return systemFileuploadMapper.findById(id);
		} else {
			return null;
		}
	}
	
	@Transactional(rollbackFor = Exception.class)
	public String insert(MultipartFile multipartFile) throws Exception {
		String id = CommonUtil.createUuid();
		String fileName = multipartFile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		// 取绝对路径
		String filePath = folderFilePath(suffix);
		String accessUrl = folderAccessUrl(filePath);
		String newFileName = newFileName(filePath);
		File f = new File(filePath);
		boolean flag = saveFile(multipartFile, filePath);
		float fileSize = f.length();
		if(flag) {
			// 保存成功
			SystemFileupload sf = new SystemFileupload();
			sf.setId(id);
			sf.setAccessurl(accessUrl);
			sf.setFilename(fileName);
			sf.setCreatename(newFileName);
			sf.setFilesuffix(suffix);
			sf.setFilepath(filePath);
			sf.setFilesize(fileSize + "");
			systemFileuploadMapper.insert(sf);
			return id;
		} else {
			// 保存失败
			throw new RequestSystemException("文件上传失败");
		}
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void insertWithPath(MultipartFile multipartFile, String filePath) throws Exception {
		// 取绝对路径
		boolean flag = saveFile(multipartFile, filePath);
		if(!flag) {
			// 保存失败
			throw new RequestSystemException("文件上传失败");
		}
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void updateSource(String id) throws Exception {
		systemFileuploadMapper.updateSource(id);
	}
	

	/**
	 * 返回格式：/nfs/img/download/YYYY-MM-DD/UUID.suffix
	 * @param fileName
	 * @param loginInfo
	 * @return
	 */
	private String folderFilePath(String suffix) {
		// fileLocalPath：文件夹绝对路径（如：D:/GC）
		// fileLocalFolder：存储文件夹路径（如：/img）
		String mainFolder = fileLocalPath + fileLocalFolder;
		// 取YYYY-MM-DD
		SimpleDateFormat formatDIR = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String dateDir = formatDIR.format(date);
		// 取文件后缀
		String newFileName = CommonUtil.createUuid() + "." + suffix;
		
		return mainFolder + "/" + dateDir + "/" + newFileName;
	}
	
	private String folderAccessUrl(String filePath) {
		return StringUtils.replace(filePath, fileLocalPath, "");
	}
	
	private String newFileName(String filePath) {
		return StringUtils.substring(filePath, StringUtils.lastIndexOf(filePath, "/") + 1);
	}
	
    private boolean saveFile(MultipartFile file, String imagePath)
			throws IllegalStateException, IOException {
		try {
			if (file.isEmpty()) {
				return false;
			}
			File f = new File(imagePath);
			if (f.getParentFile() != null) {
	            f.getParentFile().mkdirs();
	        }
			file.transferTo(f);
		} catch(Exception e) {
			return false;
		}
		return true;
	}
	
	public byte[] getFileBytes(String id) throws Exception {
		byte[] rtn = null;
		if(StringUtils.isNotBlank(id)) {
			SystemFileupload systemFileupload = systemFileuploadMapper.findById(id);
			if(systemFileupload != null) {
				File file = new File(systemFileupload.getFilepath());
				if(file.length() > 0) {
					rtn = FileUtil.fileToByte(file);
				}
			}
		}
		return rtn;
	}
	
	public void getFileStream(String id, HttpServletResponse response) throws Exception{
		if(StringUtils.isNotBlank(id)) {
			SystemFileupload systemFileupload = systemFileuploadMapper.findById(id);
			if(systemFileupload != null) {
				File file = new File(systemFileupload.getFilepath());
				if(file.length() > 0) {
					StringUtil.writeBytesToResponse(response, FileUtil.fileToByte(file), systemFileupload.getFilename());
				}
			}
		}
	}
	
	public void getFileStreamByAccessUrl(String accessUrl, String fileName, HttpServletResponse response) throws Exception{
		if(StringUtils.isNotBlank(accessUrl)) {
			File file = new File("/data" + accessUrl);
			if(file != null && file.exists() && file.length() > 0) {
				StringUtil.writeBytesToResponse(response, FileUtil.fileToByte(file), fileName);
			}
		}
	}
	
	public List<SystemFileupload> findByDate(String date) throws Exception{
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("gmtCreate", date);
		return systemFileuploadMapper.findByDate(param);
	}
}
